<template>
  <el-select
      :value="value"
      :multiple="multiple"
      :disabled="disabled"
      :placeholder="placeholder"
      @change="change"
      clearable
  >
    <el-option
        v-for="option in options"
        :key="option.lxxdm"
        :label="option.lxxmc"
        :value="option.lxxdm"
    >
      <span style="float: left">{{ option.lxxmc }}</span>
      <span v-show="showCode" style="float: right; color: #8492a6; font-size: 13px">{{ option.lxxdm }}</span>
    </el-option>
  </el-select>
</template>

<script>
import {getDefBIzdictByLxdm} from "@/api/system";

export default {
  name: "DictSelect",
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      type: [String, Array],
      required: false,
      default: ''
    },
    dictCode: {
      type: String,
      required: true
    },
    disabled: {
      type: Boolean,
      required: false,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    showCode: {
      type: Boolean,
      default: false
    },
    placeholder:{
      type: String,
      default: '请选择'
    }
  },
  data() {
    return {
      options: [{
        lxxdm: "",
        lxxmc: ""
      }]  // 字典存放数组
    }
  },
  mounted() {
    this.getDictData();
  },
  methods: {
    change(value) {
      if (this.multiple) {
        const list = value.map(key => {
          const foundItem = this.options.find(item => item.lxxdm === key);
          return {key, value: foundItem};
        });
        this.$emit('change', value, list);
      } else {
        const foundItem = this.options.find(item => item.lxxdm === value);
        const label = foundItem ? foundItem.lxxmc : "";
        this.$emit('change', value, label);
      }
    },
    async getDictData() {
      let params = {
        lxdm: this.dictCode
      }
      let {data, code, message} = await getDefBIzdictByLxdm(params);
      if (code == 200) {
        this.options = data;  // 更新options数组
      } else {
        console.error(message);
      }
    }
  }
};
</script>